package org.file_service.connection;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class RemoteShellTool {
    private Connection conn;
    private String ipAddr;
    private String charset;
    //private String charset = Charset.defaultCharset().toString();
    private String userName;
    private String password;

    public RemoteShellTool(String ipAddr, String userName, String password,
                           String charset) {
        this.ipAddr = ipAddr;
        this.userName = userName;
        this.password = password;
        if (charset != null) {
            this.charset = charset;
        }
    }

    public boolean login() throws IOException {
        conn = new Connection(ipAddr); //默认端口22
        conn.connect(); // 连接
        return conn.authenticateWithPassword(userName, password); // 认证
    }

    public void close() {
        conn.close();
    }

    public void execShell(String cmds) {
        try {
            Session session = conn.openSession(); // 打开一个会话
            session.requestDumbPTY();
            session.startShell();
            PrintWriter pw = new PrintWriter(session.getStdin());
            pw.println(cmds);
            pw.close();
            session.close();

        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    //获取查询结果
    public String exec(String cmds) {
        InputStream in = null;
        String result = "";
        try {
            Session session = conn.openSession(); // 打开一个会话
            session.execCommand(cmds);
            in = session.getStdout();
//            result = processStdout(in, cmds);
            result = processStdout(in, this.charset);
            in.close();
            session.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return result;
    }


    public String processStdout(InputStream in, String charset) {
        byte[] buf = new byte[1024];
        StringBuffer sb = new StringBuffer();
        try {
            while (in.read(buf) != -1) {
                sb.append(new String(buf, charset));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}